package com.siyuan.blog.web;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.siyuan.blog.common.vo.JSONResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 创建人：田轩
 * 创建时间：2017/11/13
 * 描述：
 */
@ControllerAdvice
public class ExceptionController {
    private static Logger log = LoggerFactory.getLogger(ExceptionController.class);  //日志记录

    @ExceptionHandler
    public void exceptionHandler(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        e.printStackTrace();
        log.debug(e.getStackTrace().toString());
        boolean isAjax = ("XMLHttpRequest".equals(request.getHeader("X-Requested-with"))) ? true : false;
        //报500错误了
        if(isAjax){ //如果是ajax请求则返回
            JSONResponse jsonModel = new JSONResponse(JSONResponse.CODE_500,"服务器错误");
            writeJson(jsonModel,response);
        }else {
            response.sendError(500);  //发送500异常
        }
    }


    /**
     * 输出json
     * @param jsonModel
     * @param resp
     * @throws IOException
     */
    private void writeJson(Object jsonModel, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/json");
        PrintWriter writer = resp.getWriter();
        String json = new ObjectMapper().writeValueAsString(jsonModel);
        writer.write(json);
        writer.close();
    }

}
